
import { message } from 'antd';
import qs from 'qs'

/** 封装fetch请求 */
function sendFetch(url, params = null, method = 'GET') {
  return new Promise(async (resolve, reject) => {
    // 配置的参数
    let config = {
      headers: {
        'authorization': localStorage.getItem('token') || "",
      },
    };
    // 判断请求类型
    if(method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') {
      if(params) {
        url += "?" + qs.stringify(params);
      }
    }
    else if(method.toUpperCase() === 'POST' || method.toUpperCase() === 'PUT') {
      config = {
        method,
        headers: {
          'Content-Type': 'application/json',
          ...config.headers,
        },
      };
      if(params) {
        config = {
          ...config,
          body: JSON.stringify(params),
        };
      }
    }

    try {
      const response = await fetch(url, {
        mode: 'cors',
        ...config,
      });
      response.json().then(res => {
        if (res.code === 200) {
          resolve(res);
        } else {
          message.error(res.message)
          reject(res);
        }
      }).catch(error => {
        reject(error);
      });
    } catch(error) {
      reject(error);
    }
  });
}


// 导出配置好的对象
export default sendFetch;